package com.example.sihookuiklydemo

import android.app.UiModeManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.res.Configuration
import android.content.res.Resources
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.Log
import android.view.Display
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle

import androidx.window.layout.FoldingFeature
import androidx.window.layout.WindowInfoTracker
import com.tencent.kuikly.core.render.android.IKuiklyRenderExport
import com.tencent.kuikly.core.render.android.adapter.KuiklyRenderAdapterManager
import com.tencent.kuikly.core.render.android.css.ktx.toMap
import com.tencent.kuikly.core.render.android.expand.KuiklyRenderViewBaseDelegatorDelegate
import com.tencent.kuikly.core.render.android.expand.KuiklyRenderViewBaseDelegator
import com.example.sihookuiklydemo.adapter.KRColorParserAdapter
import com.example.sihookuiklydemo.adapter.KRFontAdapter
import com.example.sihookuiklydemo.adapter.KRImageAdapter
import com.example.sihookuiklydemo.adapter.KRLogAdapter
import com.example.sihookuiklydemo.adapter.KRRouterAdapter
import com.example.sihookuiklydemo.adapter.KRThreadAdapter
import com.example.sihookuiklydemo.adapter.KRUncaughtExceptionHandlerAdapter
import com.example.sihookuiklydemo.module.KRBridgeModule
import com.example.sihookuiklydemo.module.KRShareModule

import com.tencent.kuikly.core.render.android.css.ktx.toList
import com.tencent.kuikly.core.render.android.expand.module.KRNotifyModule

import com.tencent.kuikly.core.render.android.expand.module.getKuiklyEventName
import com.tencent.kuikly.core.render.android.expand.module.getKuiklyEventParams
import com.tencent.kuikly.core.render.android.expand.module.registerKuiklyBroadcastReceiver
import com.tencent.kuikly.core.render.android.expand.module.unregisterKuiklyBroadcastReceiver
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.jessyan.autosize.AutoSizeCompat
import me.jessyan.autosize.AutoSizeConfig

import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

class KuiklyRenderActivity : AppCompatActivity(), KuiklyRenderViewBaseDelegatorDelegate {

    private lateinit var hrContainerView: ViewGroup
    private lateinit var loadingView: View
    private lateinit var errorView: View

    private val kuiklyRenderViewDelegator = KuiklyRenderViewBaseDelegator(this)

    private val pageName: String
        get() {
            val pn = intent.getStringExtra(KEY_PAGE_NAME) ?: ""
            return if (pn.isNotEmpty()) {
                return pn
            } else {
                "router"
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_hr)
        isCustomAdapter=isPad(this)
        listen()
        setupImmersiveMode()
        hrContainerView = findViewById(R.id.hr_container)
        loadingView = findViewById(R.id.hr_loading)
        errorView = findViewById(R.id.hr_error)
        kuiklyRenderViewDelegator.onAttach(hrContainerView, "", pageName, createPageData())
        //registerKuiklyBroadcastReceiver(kuiklyReceiver)
        val filter = IntentFilter(KRNotifyModule.BROADCAST_RECEIVER_ACTION)
        var BROADCAST_PERMISSION = "${applicationContext.packageName}.permission.KUIKLY_NOTIFY"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            registerReceiver(
                kuiklyReceiver,
                filter,
                BROADCAST_PERMISSION,
                null,
                Context.RECEIVER_EXPORTED
            )
        } else {
            registerReceiver(kuiklyReceiver, filter, BROADCAST_PERMISSION, null)
        }

        Log.i("KuiklyRenderActivity","KuiklyRenderActivity create")
    }

    override fun onDestroy() {
        super.onDestroy()
        kuiklyRenderViewDelegator.onDetach()
        unregisterKuiklyBroadcastReceiver(kuiklyReceiver)
    }

    override fun onPause() {
        super.onPause()
        kuiklyRenderViewDelegator.onPause()
    }

    override fun onResume() {
        super.onResume()
        kuiklyRenderViewDelegator.onResume()
    }

    override fun registerExternalModule(kuiklyRenderExport: IKuiklyRenderExport) {
        super.registerExternalModule(kuiklyRenderExport)
        with(kuiklyRenderExport) {
            moduleExport(KRBridgeModule.MODULE_NAME) {
                KRBridgeModule()
            }
            moduleExport(KRShareModule.MODULE_NAME) {
                KRShareModule()
            }

        }

    }

    fun listen() {
        lifecycleScope.launch(Dispatchers.Main) {
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
                // Safely collects from windowInfoRepo when the lifecycle is STARTED
                // and stops collection when the lifecycle is STOPPED
                WindowInfoTracker.getOrCreate(this@KuiklyRenderActivity)
                    .windowLayoutInfo(this@KuiklyRenderActivity)
                    .collect { layoutInfo ->
                        // New posture information
                        val foldingFeature = layoutInfo.displayFeatures
                        runOnUiThread {
                            if (foldingFeature.isNullOrEmpty()) {
                                Log.i(TAG, "listen: foldingFeature isNullOrEmpty")

                            } else {
                                var displayFeature = foldingFeature[0]
                                if (displayFeature is FoldingFeature) {
                                    isFoldDevice = true
                                    Log.i(TAG, "listen: foldingFeature")
                                }

                            }

                        }
                    }
            }
        }
    }
    override fun registerExternalRenderView(kuiklyRenderExport: IKuiklyRenderExport) {
        super.registerExternalRenderView(kuiklyRenderExport)
        with(kuiklyRenderExport) {

        }
    }

    var isFoldDevice = true

    private fun createPageData(): Map<String, Any> {
        val param = argsToMap()
        var darkMode=AppCompatDelegate.getDefaultNightMode()
        param["appId"] = 1
        param["equipmentId"] = 1
        param["userId"] = 50014
        param["token"] = "800624b5b8042fd4f22810351fc7b39b75d55abd85dfdab3f2173455abeb8485"
        param["isPad"] = isPad(this)
        param["isFoldDevice"] = isFoldDevice
        param["NightMode"] = darkMode
        var isDarkMode= isDarkMode()
        Log.i(TAG, "isDarkMode: $darkMode ${isDarkMode}")
        param["isNightMode"] = isDarkMode
        return param
    }
    fun isDarkMode(): Boolean {
        var darkMode = AppCompatDelegate.getDefaultNightMode()
        var uiModeManager = getSystemService(Context.UI_MODE_SERVICE) as UiModeManager
        if (darkMode == AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) {
            return uiModeManager.nightMode == AppCompatDelegate.MODE_NIGHT_YES
        }
        Log.i(TAG, "isDarkMode: $darkMode ${uiModeManager.nightMode}")
        return darkMode == AppCompatDelegate.MODE_NIGHT_YES
    }
    open fun isPad(context: Context): Boolean {
        val isPad: Boolean = (context.resources.configuration.screenLayout
                and Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE
        val wm: WindowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val display: Display = wm.getDefaultDisplay()
        val dm = DisplayMetrics()
        display.getMetrics(dm)
        val x = Math.pow((dm.widthPixels / dm.xdpi).toDouble(), 2.0)
        val y = Math.pow((dm.heightPixels / dm.ydpi).toDouble(), 2.0)
        val screenInches = Math.sqrt(x + y) // 屏幕尺寸
        return isPad || screenInches >= 7.0
    }

    private fun argsToMap(): MutableMap<String, Any> {
        val jsonStr = intent.getStringExtra(KEY_PAGE_DATA) ?: return mutableMapOf()
        return JSONObject(jsonStr).toMap()
    }

    private fun setupImmersiveMode() {
        window?.apply {
            addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window?.statusBarColor = Color.TRANSPARENT
            window?.decorView?.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        }

    }

    companion object {

        private const val KEY_PAGE_NAME = "pageName"
        private const val KEY_PAGE_DATA = "pageData"

        init {
            initKuiklyAdapter()
        }

        fun start(context: Context, pageName: String, pageData: JSONObject) {
            val starter = Intent(context, KuiklyRenderActivity::class.java)
            starter.putExtra(KEY_PAGE_NAME, pageName)
            starter.putExtra(KEY_PAGE_DATA, pageData.toString())
            context.startActivity(starter)
        }

        private fun initKuiklyAdapter() {
            with(KuiklyRenderAdapterManager) {
                krImageAdapter = KRImageAdapter
                krLogAdapter = KRLogAdapter
                krUncaughtExceptionHandlerAdapter = KRUncaughtExceptionHandlerAdapter

                krFontAdapter = KRFontAdapter
                krColorParseAdapter = KRColorParserAdapter(KRApplication.application)
                krRouterAdapter = KRRouterAdapter
                krThreadAdapter = KRThreadAdapter()
            }
        }
    }

    var isCustomAdapter = false
    var customSizeInDp = 767f
    override fun getResources(): Resources {
        //info(TAG, "getResources: ${this.javaClass}")
        //需要升级到 v1.1.2 及以上版本才能使用 AutoSizeCompat
        when (isCustomAdapter) {
            true -> {
                runOnUiThread {
                    AutoSizeCompat.autoConvertDensity(
                        super.getResources(),
                        customSizeInDp,
                        false
                    );
                }
            }

            else -> {

                /*
                 )*/
                runOnUiThread {
                    if (isFoldDevice) {
                        AutoSizeCompat.autoConvertDensityBaseOnHeight(
                            super.getResources(),
                            AutoSizeConfig.getInstance().designHeightInDp.toFloat()
                        )
                    } else {
                        AutoSizeCompat.autoConvertDensityOfGlobal(super.getResources())
                    }
                }
            }
        }


        return super.getResources()
    }

    private val TAG = "KuiklyRenderActivity"
    val kuiklyReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {

            val eventName = intent.getKuiklyEventName() // 接收到的事件名字
            Log.i(TAG, "onReceive: ${eventName}")
            val data = intent.getKuiklyEventParams() // kuikly侧传递的参数
            Log.i("TAG", "收到通知 ${data}")
            when (eventName) {
                "UpdateDeviceInfo"->{
                    var deskName = data.optString("nameV2")
                    var eqId = data.optInt("equipmentId")
                    eqId?.let {

                    }
                }
                "BLE_OP_LIST" -> {
                    Log.i(TAG, "BLE_OP_LIST ${data}")
                    var sendValueArray = data.optJSONArray("sendValueArray")
                    var sendData = data.get("sendValueArray")
                    Log.i("BLE_OP_LIST", "$sendData")
                    sendValueArray?.toList()?.forEach {
                        Log.i(
                            "BLE_OP_LIST",
                            "${jsonConvertStringListToByteArray(it.toString()).toHex()}"
                        )
                    }
                }

                "BLE_OP" -> {

                    var sendValue = data.opt("sendValue")
                    var sendValueArray = data.optJSONArray("sendValueArray")
                    Log.i(TAG, "${data} sendValue $sendValue")

                    sendValue?.let {
                        Log.i(
                            TAG,
                            "${jsonConvertStringListToByteArray(sendValue as String).toHex()}"
                        )

                    }
                    sendValueArray?.toList()?.forEach {
                        Log.i(TAG, "${jsonConvertStringListToByteArray(it.toString()).toHex()}")
                    }


                }

            }
        }
    }

    fun ByteArray.toHex() = joinToString("") { String.format("%02X ", (it.toInt() and 0xff)) }

    /**
     * 方法3：使用JSON解析（最健壮的方法）
     */
    fun jsonConvertStringListToByteArray(input: String): ByteArray {
        return try {
            // 使用JSON数组解析
            val jsonArray = JSONArray(input)
            ByteArray(jsonArray.length()) { index ->
                when (val item = jsonArray.get(index)) {
                    is Int -> item.toByte()
                    is String -> item.toInt().toByte()
                    else -> throw IllegalArgumentException("无效元素类型: $item")
                }
            }
        } catch (e: JSONException) {
            throw IllegalArgumentException("无效的JSON格式", e)
        }
    }

}